using System.Threading.Tasks;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Domain.Entities.App;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data.Contexts;
using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Shared.Enums;

namespace UniversalAdmin.Application.Services;

public class AppRolePermissionServices : IAppRolePermissionServices
{
    private readonly IRepository<AppRole> _roleRepository;
    private readonly AdminDbContext _db;
    
    public AppRolePermissionServices(IRepository<AppRole> roleRepository, AdminDbContext db)
    {
        _roleRepository = roleRepository;
        _db = db;
    }

    public Task<ApiResult> AssignPermissionsAsync(AssignRolePermissionsDto dto)
        => Task.FromResult(ApiResult.Success("分配权限成功"));

    public async Task<ApiResult<IEnumerable<object>>> GetRolePermissionsAsync(Guid roleId)
    {
        // 使用AdminDbContext直接查询，确保加载关联的权限数据
        var role = await _db.AppRoles
            .Include(r => r.Permissions)
            .FirstOrDefaultAsync(r => r.Id == roleId);
            
        if (role == null) 
            return ApiResult<IEnumerable<object>>.Failed((int)ApiStatusCode.NOT_FOUND, "角色不存在");
            
        if (role.IsDelete)
            return ApiResult<IEnumerable<object>>.Failed((int)ApiStatusCode.CONFLICT, "角色已被删除");
            
        // 返回包含ID和编码的权限信息
        var permissions = role.Permissions
            .Where(p => p.IsActive && !p.IsDelete)
            .Select(p => new
            {
                Id = p.Id,
                Code = p.PermissionCode,
                Name = p.PermissionName
            })
            .ToList();
            
        return ApiResult<IEnumerable<object>>.Success((int)ApiStatusCode.SUCCESS, "获取角色权限成功", permissions);
    }

    /// <summary>
    /// 获取角色的详细权限信息
    /// </summary>
    /// <param name="roleId">角色ID</param>
    /// <returns>权限详细信息列表</returns>
    public async Task<ApiResult<IEnumerable<PermissionDto>>> GetRolePermissionsDetailAsync(Guid roleId)
    {
        // 使用AdminDbContext直接查询，确保加载关联的权限数据
        var role = await _db.AppRoles
            .Include(r => r.Permissions)
            .FirstOrDefaultAsync(r => r.Id == roleId);
            
        if (role == null) 
            return ApiResult<IEnumerable<PermissionDto>>.Failed((int)ApiStatusCode.NOT_FOUND, "角色不存在");
            
        if (role.IsDelete)
            return ApiResult<IEnumerable<PermissionDto>>.Failed((int)ApiStatusCode.CONFLICT, "角色已被删除");
            
        // 返回详细的权限信息
        var permissions = role.Permissions
            .Where(p => p.IsActive && !p.IsDelete)
            .Select(p => new PermissionDto
            {
                Id = p.Id,
                Name = p.PermissionName,
                Code = p.PermissionCode,
                CreatedAt = p.CreatedAt,
                UpdatedAt = p.UpdatedAt,
                IsActive = p.IsActive
            })
            .ToList();
            
        return ApiResult<IEnumerable<PermissionDto>>.Success((int)ApiStatusCode.SUCCESS, "获取角色权限成功", permissions);
    }

    public async Task<ApiResult> RemoveRolePermissionAsync(Guid roleId, Guid permissionId)
    {
        var role = await _db.AppRoles
            .Include(r => r.Permissions)
            .FirstOrDefaultAsync(r => r.Id == roleId);
            
        if (role == null) 
            return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "角色不存在");
            
        if (role.IsDelete)
            return ApiResult.Failed((int)ApiStatusCode.CONFLICT, "角色已被删除");
            
        var permission = role.Permissions.FirstOrDefault(p => p.Id == permissionId);
        if (permission == null) 
            return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "权限不存在");
            
        role.Permissions.Remove(permission);
        await _db.SaveChangesAsync();
        return ApiResult.Success((int)ApiStatusCode.SUCCESS, "移除权限成功");
    }
} 